﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jacaranda.Data;

namespace Jacaranda.Model
{
    public class EntityAssociation
    {
        public Type From { get; set; }

        public Type To { get; set; }

        public int Instance { get; set; }

        internal string TableName
        {
            get { return string.Format("{0}_{1}_Association{2}", 
                Metadata.Type(From).TableName, 
                Metadata.Type(To).TableName, 
                (Instance == 0) ? null : Instance.ToString()); }
        }

        public void Insert(Entity source, Entity target, Transaction transaction)
        {
            DataPortal.Execute(string.Format("INSERT INTO {0} (Key1, Key2) VALUES('{1}', '{2}')",
            TableName,
            Metadata.Type(source.GetType()).PrimaryKey.GetValue(source),
            Metadata.Type(target.GetType()).PrimaryKey.GetValue(target)), transaction);
        }

        public void Delete(Entity source, Entity target, Transaction transaction)
        {
            DataPortal.Execute(string.Format("DELETE FROM {0} WHERE Key1='{1}' AND Key2='{2}'",
            TableName,
            Metadata.Type(source.GetType()).PrimaryKey.GetValue(source),
            Metadata.Type(target.GetType()).PrimaryKey.GetValue(target)), transaction);
        }
    }
}
